
import requests
import urllib.request
import os,re,urllib

class BuDeJieDownload:
    def __init__(self,urls):
        self.urls = urls

    def get_response(self,url):
        response = requests.get(url).content
        return response

    def get_content(self,html):
        "http://222.186.190.188:8899/pic/playimg/3.jpg"
        reg = re.compile(r'(<div class="j-content">.*?</div>*?</div>)',re.S)
        # 默认不匹配换行，加re.S模式
        return re.findall(reg,str(html))

    def get_mp4_url(self,response):
        reg = r'data-mp4"(.*?)"'
        return re.findall(reg,response)

    def get_mp4_name(self,response):
        reg=re.compile('<a href="/detail-.{8}.html">(.*？)</a>')
        re.findall(reg,response)  # 返回的是列表

    def download_mp4(self,url,path):
        path =''.join(path.split())
        path ='F:/snake/{}.mp4'.format(path.decode("utf-8").encode("gbk"))
        # utf-8 ---> unicode --->gbk
        if not os.path.exists(path):
            urllib.request.urlretrieve(url,path)
            print("ok!!!!")
        else:
            print("on!!!")
    def get_url_name(self,start_url):
        content = self.get_content(self.get_response(start_url))
        for i in content:
            mp4_url = self.get_mp4_url(i)
            if not mp4_url:
                mp4_name = self.get_mp4_name(i)
                try:
                    self.download_mp4(mp4_url[0], mp4_name[0])
                except:
                    content

    def main(self):
        [self.get_url_name(start_url) for start_url in start_urls]

if __name__ == '__main__':
    start_urls = ["http://www.budejie.com/{}".format(i) for i in range(1,10)]
    download=BuDeJieDownload(start_urls)
    download.main()


